<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      height: 2000px;
    }

    #btn {
      width: 50px;
      height: 50px;
      background-color: #ddd;
      line-height: 50px;
      text-align: center;
      position: fixed;
      right: 10px;
      bottom: 10px;
      display: none;
    }
  </style>
  <script>
    window.onload = function () {
      var btn = document.getElementById('btn');
      var html = document.documentElement;
      var body = document.body;
      // 获取可视区大小
      var clientHeight = html.clientHeight || body.clientHeight;
      // 定时器
      timer = null;
      // 是否可以返回顶部
      var isTop = true;

      // 窗口滚动
      window.onscroll = function () {
        // 获取页面滚动的距离
        var scrollTop = html.scrollTop || body.scrollTop;
        // 按钮显示隐藏
        btn.style.display = scrollTop > clientHeight ? 'block' : 'none';
        // 返回顶部过程，是否滚动页面了
        if (!isTop) {
          clearInterval(timer);
        }
        isTop = false;
      }

      // 点击
      btn.onclick = function () {
        timer = setInterval(function () {
          // 获取页面滚动的距离
          var scrollTop = html.scrollTop || body.scrollTop;
          // 设置每次滚动的距离
          var speed = parseInt(-scrollTop / 6);
          // 设置距离顶部
          html.scrollTop = body.scrollTop = scrollTop + speed;
          isTop = true;
          // 判断是否回到顶部
          if (scrollTop == 0) {
            clearInterval(timer);
          }
        }, 50)
      }
    }
  </script>
</head>

<body>
  <div id="btn">TOP</div>
</body>

</html>